<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%
	// 绑定第三方账户
	Integer id = token.getUid();
	String source = input.getDesc("source", "");
	String unionId = input.getDesc("union_id", "");
	if (!"weibo".equals(source) && !"qq".equals(source) && !"wechat".equals(source)) {
		Tools.encryptPrint(out, new Message(30041, "第三方来源不合法"));
		return;
	}
	if ("".equals(unionId)) {
		Tools.encryptPrint(out, new Message(30041, "第三方唯一标识不合法"));
		return;
	}
	User self = userByUid(id);
	if (self == null ) {
		Tools.encryptPrint(out, new Message(30041, "用户不存在"));
		return;
	}
	Integer userType = self.getType();
	List isBindList = QBuilder.db("basedb").select().from("UserAccount as ua").where(new Where("ua.hospital=", hospital).and("ua.source=", source).and("ua.status=", STATUS_ENABLE).and("ua.uid=", id)).query().getResultObj();
	if (!isEmpty(isBindList)) {
		Tools.encryptPrint(out, new Message(30041, "你已经绑定过该类型的账号"));
		return;
	}
	List list = QBuilder.db("basedb").select("new map(ua.id as id)").from("UserAccount as ua, User as u").where(new Where("ua.hospital=", hospital).and("ua.source=", source).and("ua.unionId=", unionId).and("ua.status=", STATUS_ENABLE).and("ua.uid=u.id").and("u.hospital=", hospital).and("u.status=", STATUS_ENABLE).and("u.type=", userType)).query().getResultObj();
	if (list.size() != 0 ) {
		source = "weibo".equals(source)?"微博账号":"qq".equals(source)?"QQ账号":"微信账号" ;
		Tools.encryptPrint(out, new Message(-1, "该" +  source + "已经被用于绑定其他用户，请解绑后重试"));
		return;
	}
	// 核对微信token及openid合法性
	if ("wechat".equals(source)) {
		String accessToken = input.getDesc("access_token");
		String res = HttpUtil.get("https://api.weixin.qq.com/sns/auth?access_token=" + accessToken + "&openid=" + unionId);
		Map wechatMap = JSONUtil.fromJson(res, new TypeReference<Map>(){});
		if ((Integer)wechatMap.get("errcode") != 0) {
			Tools.encryptPrint(out, new Message("绑定微信失败,token无效"));
			return;
		}
	}
	UserAccount userAccount = UserAccount.fromMap(parameters, UserAccount.class);
	userAccount.setUid(id);
	DBTools.db("basedb").addItem(userAccount);
	Tools.encryptPrint(out, msg);
%>